<template>
  <div class="worker-home-container">
    <!-- 顶部导航栏保持不变 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.png" alt="家政服务平" />
          <span>家政服务平台</span>
        </div>
        <el-icon><Menu /></el-icon>
        <el-icon><Refresh /></el-icon>
        <span class="nav-text">我的主页</span>
      </div>
      <div class="header-right">
        <el-badge :value="notifications.length" :hidden="!notifications.length">
          <el-icon><Bell /></el-icon>
        </el-badge>
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <el-avatar :size="32" :src="workerAvatar">{{ userInitials }}</el-avatar>
            <span>{{ workerInfo.name || '家政人员' }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="settings">账号设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span style="color: #f56c6c;">注销</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单保持不变 -->
      <el-aside width="200px" class="sidebar">
        <div class="worker-profile">
          <el-avatar :size="64" :src="workerAvatar">
            {{ userInitials }}
          </el-avatar>
          <div class="worker-name">{{ workerInfo.name || '未设置姓名' }}</div>
          <div class="worker-status" :class="statusClass">
            {{ getStatusText(workerInfo.status) }}
          </div>
        </div>
        <el-menu default-active="1">
          <el-menu-item index="1">
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <!-- 个人信息卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <div class="action-buttons">
                <el-tag v-if="workerInfo.status" :type="getStatusType(workerInfo.status)">
                  {{ getStatusText(workerInfo.status) }}
                </el-tag>
                <el-button v-if="!isEditing" type="primary" @click="startEditing">修改信息</el-button>
              </div>
            </div>
          </template>

          <el-form
              ref="infoFormRef"
              :model="workerForm"
              :rules="formRules"
              :disabled="!isEditing"
              label-width="100px"
              label-position="right"
              status-icon
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="workerForm.name" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="workerForm.phone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="workerForm.idCard" placeholder="请输入身份证号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="workerForm.gender" placeholder="请选择性别">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input-number v-model="workerForm.age" :min="18" :max="65" placeholder="请输入年龄" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="workerForm.status" placeholder="请选择状态">
                    <el-option label="在职" value="在职" />
                    <el-option label="休假" value="休假" />
                    <el-option label="离职" value="离职" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="服务地址" prop="address">
              <el-input v-model="workerForm.address" placeholder="请输入服务地址" />
            </el-form-item>

            <el-form-item label="服务类型" prop="serviceType">
              <el-select
                  v-model="workerForm.serviceType"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="请选择服务类型"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in serviceTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="工作经验" prop="workExperience">
              <el-input
                  v-model="workerForm.workExperience"
                  type="textarea"
                  :rows="4"
                  placeholder="请描述您的工作经验，包括专业技能、服务年限等"
              />
            </el-form-item>

            <el-form-item label="证件照片" v-if="isEditing">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8092/common/upload"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="workerForm.image" :src="workerForm.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">请上传清晰的证件照片（正面免冠照）</div>
            </el-form-item>

            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="submitForm">提交审核</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 审核状态卡片 -->
        <el-card v-if="workerInfo.status" class="status-card">
          <template #header>
            <div class="card-header">
              <span>审核进度</span>
            </div>
          </template>

          <el-steps :active="getStatusStep(workerInfo.status)" finish-status="success">
            <el-step title="信息提交" description="填写并提交个人信息" />
            <el-step title="资料审核中" description="管理员正在审核您的信息" />
            <el-step title="审核通过" description="您可以开始接单了" />
          </el-steps>

          <div v-if="workerInfo.status === '已拒绝'" class="rejection-info">
            <el-alert
                title="审核未通过"
                type="error"
                description="您的信息审核未通过，请修改后重新提交。"
                show-icon
                :closable="false"
            />
            <div class="rejection-reason" v-if="workerInfo.rejectionReason">
              <h4>拒绝原因：</h4>
              <p>{{ workerInfo.rejectionReason }}</p>
            </div>
          </div>
        </el-card>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Menu, Refresh, Bell, CaretBottom, User, Calendar,
  Document, ChatDotRound, Setting, Plus
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {insertWorkerApplication} from "@/api/worker-application/work-application.js";
import {userLogout} from "@/api/user/user.js";
import {getWorkerByRedis} from "@/api/worker/worker.js";

const router = useRouter()
const infoFormRef = ref(null)
const isEditing = ref(false)
const workerAvatar = ref('')
const loading = ref(false)
const hasSubmittedApplication = ref(false)
const applicationId = ref(null)

// 上传请求头，用于携带token
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  }
})

// 服务类型选项
const serviceTypeOptions = [
  { label: '清洁服务', value: '清洁服务' },
  { label: '照护服务', value: '照护服务' },
  { label: '烹饪服务', value: '烹饪服务' },
  { label: '维修服务', value: '维修服务' },
  { label: '其他服务', value: '其他服务' }
]

// 家政人员信息数据结构
const workerInfo = reactive({
  id: null,
  name: '',
  phone: '',
  idCard: '',
  image: '',
  gender: '女',
  age: 0,
  address: '',
  serviceType: [],
  workExperience: '',
  joinDate: null,
  status: null,
  rejectionReason: '',
})

// 表单数据对象
const workerForm = reactive({
  name: '',
  phone: '',
  idCard: '',
  gender: '女',
  age: 30,
  address: '',
  serviceType: [],
  workExperience: '',
  status: '在职',
  image: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 15, message: '姓名长度应为2-15个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 18, max: 65, message: '年龄必须在18-65岁之间', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入服务地址', trigger: 'blur' }
  ],
  serviceType: [
    { required: true, message: '请至少选择一种服务类型', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一种服务类型', trigger: 'change' }
  ],
  workExperience: [
    { required: true, message: '请填写工作经验', trigger: 'blur' },
    { min: 10, message: '工作经验描述不能少于10个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算头像显示的首字母
const userInitials = computed(() => {
  return workerInfo.name ? workerInfo.name.charAt(0).toUpperCase() : 'W'
})

// 计算状态样式
const statusClass = computed(() => {
  switch(workerInfo.status) {
    case '已通过': return 'status-approved'
    case '已拒绝': return 'status-rejected'
    default: return 'status-pending'
  }
})

// 获取状态文本
const getStatusText = (status) => {
  if (!status) return '未提交'
  switch(status) {
    case '已通过': return '审核通过'
    case '已拒绝': return '审核未通过'
    case '待审批': return '审核中'
    default: return status
  }
}

// 获取状态类型（用于 el-tag）
const getStatusType = (status) => {
  switch(status) {
    case '已通过': return 'success'
    case '已拒绝': return 'danger'
    case '待审批': return 'warning'
    default: return 'info'
  }
}

// 获取审核步骤
const getStatusStep = (status) => {
  switch(status) {
    case '已通过': return 3
    case '待审批': return 2
    case '已拒绝': return 1
    default: return 1
  }
}

// 获取家政人员信息
const fetchWorkerInfo = async () => {
  loading.value = true
  try {
    const response = await getWorkerByRedis()
    console.log('API返回数据:', response.data) // 调试日志

    if (response.data.code === 200 && response.data.data) {
      const data = response.data.data

      // 填充工作者信息
      Object.assign(workerInfo, {
        id: data.id,
        name: data.name || '',
        phone: data.phone || '',
        idCard: data.idCard || '',
        gender: data.gender || '女',
        age: data.age || 0,
        address: data.address || '',
        serviceType: data.serviceType ? [data.serviceType] : [], // 服务类型可能是单个字符串
        workExperience: data.workExperience || '',
        joinDate: data.joinDate || null,
        status: data.status || '',
        image: data.image || ''
      })

      console.log('处理后的工作人员信息:', workerInfo) // 调试日志

      // 更新表单数据
      Object.assign(workerForm, {
        name: workerInfo.name,
        phone: workerInfo.phone,
        idCard: workerInfo.idCard,
        gender: workerInfo.gender,
        age: workerInfo.age,
        address: workerInfo.address,
        serviceType: workerInfo.serviceType,
        workExperience: workerInfo.workExperience,
        status: workerInfo.status,
        image: workerInfo.image
      })

      // 如果有头像，获取头像URL
      if (data.image) {
        workerAvatar.value = data.image
        workerForm.image = data.image
      }

      // // 获取通知
      // fetchNotifications()
    } else {
      //ElMessage.warning(response.data.message || '获取信息失败')
    }
  } catch (error) {
    console.error('获取家政人员信息失败:', error)
    //ElMessage.error('获取家政人员信息失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 开始编辑
const startEditing = () => {
  if (workerInfo.status === '待审批') {
    ElMessageBox.confirm('您的信息正在审核中，修改信息将重新提交审核，是否继续？', '提示', {
      confirmButtonText: '继续',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      isEditing.value = true
    }).catch(() => {})
    return
  }
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  // 重置表单
  Object.assign(workerForm, {
    name: workerInfo.name || '',
    phone: workerInfo.phone || '',
    idCard: workerInfo.idCard || '',
    gender: workerInfo.gender || '女',
    age: workerInfo.age || 30,
    address: workerInfo.address || '',
    serviceType: workerInfo.serviceType || [],
    workExperience: workerInfo.workExperience || '',
    status: workerInfo.status || '在职',
    image: workerInfo.image || ''
  })
  isEditing.value = false
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  console.log('上传成功:', response)
  if (response && response.code === 200) {
    // 设置图片URL到表单
    workerForm.image = response.data
    // 更新头像预览
    workerAvatar.value = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.message || '未知错误'))
  }
}

// 上传失败回调
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('头像上传失败，请稍后重试')
}

// 提交表单
const submitForm = async () => {
  if (!infoFormRef.value) return

  await infoFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm('确认提交个人信息进行审核？', '提交确认', {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        try {
          loading.value = true

          // 准备请求数据
          const requestData = {
            id: workerInfo.id,
            name: workerForm.name,
            phone: workerForm.phone,
            idCard: workerForm.idCard,
            gender: workerForm.gender,
            age: workerForm.age,
            address: workerForm.address,
            serviceType: Array.isArray(workerForm.serviceType)
                ? workerForm.serviceType.join(',')
                : workerForm.serviceType,
            workExperience: workerForm.workExperience,
            status: workerForm.status,
            joinDate: workerInfo.joinDate || new Date().toISOString().split('T')[0],
            image: workerForm.image // 直接使用表单中的图片URL
          }

          console.log('提交的申请数据:', requestData) // 调试日志

          // 发送到更新申请接口
          const response = await insertWorkerApplication(requestData)

          if (response.data.code === 200 || response.data.success) {
            // 更新本地信息
            ElMessage({
              type: 'success',
              message: '个人信息更新申请已提交，请等待审核'
            })

            // 刷新工作人员信息
            await fetchWorkerInfo()

            isEditing.value = false
          } else {
            ElMessage.error(response.data.message || '提交失败')
          }
        } catch (error) {
          console.error('提交表单失败:', error)
          ElMessage.error('提交失败，请稍后再试: ' + (error.response?.data?.message || error.message))
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.warning('请完善表单信息')
    }
  })
}

// 通知数据
const notifications = ref([])

// // 获取通知
// const fetchNotifications = async () => {
//   try {
//     const response = await api.get('/notifications')
//     if (response.data.success) {
//       notifications.value = response.data.data
//     }
//   } catch (error) {
//     console.error('获取通知失败:', error)
//   }
// }

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    ElMessage.info('当前已在个人信息页面')
  } else if (command === 'settings') {
    ElMessage.info('账号设置功能开发中')
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await userLogout()
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('userId')

      ElMessage({
        type: 'success',
        message: '已成功退出登录'
      })
      router.push('/login')
    } catch (error) {
      console.error('退出登录失败:', error)
      // 即使API调用失败也清除本地存储并跳转
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('userId')
      router.push('/login')
    }
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  // 获取家政人员信息
  fetchWorkerInfo()
})
</script>


<style scoped>
/* 全局容器样式 */
.worker-home-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  position: absolute;
  left: 0;
  top: 0;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  z-index: 1000;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 20px;
  font-weight: bold;
  font-size: 18px;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.nav-text {
  margin-left: 15px;
}

.header-left .el-icon {
  margin-right: 15px;
  font-size: 18px;
  cursor: pointer;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-icon {
  font-size: 20px;
  margin: 0 15px;
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.user-info span {
  margin: 0 8px;
}

/* 主容器样式 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #fff;
  height: 100%;
  box-shadow: 1px 0 4px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  padding-top: 0;
  z-index: 900;
  width: 200px !important;
  flex-shrink: 0;
  margin: 0;
}

.worker-profile {
  padding: 20px 0;
  text-align: center;
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 10px;
}

.worker-name {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0 5px;
}

.worker-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.status-pending {
  background-color: #e6a23c;
  color: #fff;
}

.status-approved {
  background-color: #67c23a;
  color: #fff;
}

.status-rejected {
  background-color: #f56c6c;
  color: #fff;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}

/* 卡片样式 */
.info-card, .status-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.action-buttons .el-tag {
  margin-right: 10px;
}

/* 头像上传样式 */
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 拒绝理由样式 */
.rejection-info {
  margin-top: 20px;
}

.rejection-reason {
  margin-top: 15px;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.rejection-reason h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #f56c6c;
}

.rejection-reason p {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-steps) {
  margin-top: 20px;
}
</style>
